<script setup>
import { ref, watch } from 'vue'
import {
    userloginService,
    userregisterService,
} from '@/api/auth'

import { captchaCodeRegisterService } from '@/api/user'

import { useUserStore } from '@/stores'
import { Message, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

const formRef = ref()
const formModel = ref({
    email: '',
    password: '',
    code: ''
})

//防抖
const disabled = ref(false)

//登录
const login = async () => {
    await formRef.value.validate()
    disabled.value = true
    try {
        const result = await userloginService(formModel.value)
        // console.log('result:', result)
        await userStore.setToken(result.data)
        await userStore.getUser()
        ElMessage.success('登录成功')
        router.push('/')
    } catch (err) {
        console.error('loginError:', err)
        ElMessage.error('登录失败')
    } finally {
        formModel.value.email = ''
        formModel.value.password = ''
        disabled.value = false
    }
}

//注册
const register = async () => {
    await formRef.value.validate()
    try {
        await userregisterService(formModel.value)
        ElMessage.success('注册成功,请登录')
        isRegsiter.value = false
    } catch (err) {
        console.error('registerError', err)
    } finally {
        formModel.value = {
            password: '',
            email: '',
            code: ''
        }
    }
}

const isRegsiter = ref(false)

const rules = ref({
    code: [
        {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
        },
        {
            pattern: /^\d{6}$/,
            message: '验证码必须是6位数字',
            trigger: 'blur'
        }
    ],
    email: [
        {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
        },
        {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        },
        {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15位的非空字符',
            trigger: 'blur'
        }
    ]
})

const yz = ref({
    total: 60,
    curry: 60,
    timer: null
})

//发送验证码
const onSend = () => {
    //验证通过 err：true, 反之为：false
    formRef.value.validateField('email', async (err) => {
        if (err) {
            if (!yz.value.timer && yz.value.total === yz.value.curry) {
                disabled.value = true
                try {
                    await captchaCodeRegisterService({ email: formModel.value.email })
                    ElMessage.success('验证码已发送，一分钟之内有效，请注意查收')
                    //开启定时器
                    yz.value.timer = setInterval(() => {
                        yz.value.curry--
                        if (yz.value.curry <= 0) {
                            clearInterval(yz.value.timer)
                            yz.value.timer = null
                            yz.value.curry = yz.value.total
                            disabled.value = false
                        }
                    }, 1000)
                } finally {
                    disabled.value = false
                }
            }
        } else {
            ElMessage.error('请输入正确的邮箱地址')
            return
        }
    })
}

watch(isRegsiter, () => {
    formModel.value = {
        email: '',
        password: '',
        code: ''
    }
})
</script>
<template>
    <div class="login_container">
        <div class="login_box">
            <div class="box">
                <header class="header">
                    <router-link to="/">
                        <img style="width: 75px; height: 75px" src="@/assets/image/logo.png" alt="logo" />
                    </router-link>
                    <div class="text">
                        宠物管家
                        <p class="tesc">-- 轻松管理你的宠物 --</p>
                    </div>
                </header>

                <main class="main">
                    <el-form class="my_form" ref="formRef" :model="formModel" :rules="rules" autocomplete="false"
                        v-if="!isRegsiter" size="large">
                        <el-form-item prop="email">
                            <el-input v-model="formModel.email" placeholder="邮箱地址" :prefix-icon="Message" />
                        </el-form-item>

                        <el-form-item prop="password">
                            <el-input type="password" v-model="formModel.password" placeholder="密码" show-password
                                :prefix-icon="Lock" />
                        </el-form-item>
                        <el-form-item class="btn_group">
                            <el-button @click.prevent="isRegsiter = true" class="btn" type="warning"
                                auto-insert-space="true">去注册</el-button>
                            <el-button :disabled="disabled" @click="login" class="btn" type="primary"
                                auto-insert-space="true">
                                登录
                            </el-button>
                            <router-link style="margin-left: auto;" to="/forget">
                                忘记密码，使用验证码登录
                            </router-link>
                        </el-form-item>
                    </el-form>

                    <el-form class="my_form" ref="formRef" :model="formModel" :rules="rules" autocomplete="false" v-else
                        size="large">
                        <el-form-item prop="email">
                            <el-input v-model="formModel.email" placeholder="邮箱地址" :prefix-icon="Message" />
                        </el-form-item>
                        <el-form-item prop="code">
                            <el-input v-model="formModel.code" placeholder="请输入验证码" :prefix-icon="Grid">
                                <template #append>
                                    <el-button type="primary" :disabled="disabled" @click="onSend">{{
                                        yz.total === yz.curry ? '获取验证码' : yz.curry + 's后重新发送'
                                    }}</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input type="password" v-model="formModel.password" placeholder="密码" show-password
                                :prefix-icon="Lock" />
                        </el-form-item>
                        <el-form-item class="btn_group">
                            <el-button @click.prevent="isRegsiter = false" class="btn" type="default"
                                auto-insert-space="true">去登陆</el-button>
                            <el-button @click.prevent="register" class="btn" type="primary"
                                auto-insert-space="true">注册</el-button>
                        </el-form-item>
                    </el-form>
                </main>
            </div>
            <div class="img">
                <img src="@/assets/image/bg1.jpg" alt="" />
            </div>
        </div>
    </div>
</template>
<style scoped lang="scss">
.login_container {
    background: #36D1DC;
    /* fallback for old browsers */
    background: -webkit-linear-gradient(to right, #5B86E5, #36D1DC);
    /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(to right, #5B86E5, #36D1DC);
    /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;

    .login_box {
        box-shadow: 0 2px 16px 0 #74b4ce;
        border-radius: 20px 0 0 20px;
        display: flex;
        justify-content: space-around;

        .box {
            background-color: #fff;
            width: 25.125rem;
            padding: 2rem;
            padding-bottom: 1rem;
            letter-spacing: 2px;
            border-radius: 20px 0 0 20px;

            .header {
                display: flex;
                justify-content: center;
                margin-bottom: 1rem;

                .text {
                    color: rgb(70, 174, 216);
                    font-size: 1.5rem;
                    margin-left: 1.5rem;
                    text-align: center;

                    .tesc {
                        margin-top: 0.6rem;
                        font-size: 0.6rem;
                        color: #ccc;
                    }
                }
            }

            .main {
                .btn_group {
                    .btn {
                        width: 45%;
                    }

                    .btn:first-child {
                        margin-right: auto;
                    }
                }
            }
        }

        .img {
            width: 28.125rem;
            overflow: hidden;

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
    }
}
</style>
